Page({
  data: {
    sensorData: {
      // 阈值变量(可设置)
      CO2threshold: 800,      // 等效二氧化碳浓度阈值
      Tvocthreshold: 500,     // 有机挥发物浓度阈值
      MQthreshol: 1000,       // MQ-2阈值
      
      // 传感器数据变量(只读)
      analogValue: 0,         // MQ-2原始值
      boomswitch: 0,          // 报警开关
      Z: 0,                   // Z轴加速度(g)
      Y: 0,                   // Y轴加速度(g)
      X: 0,                   // X轴加速度(g)
      Speed: 0,               // 速度(km/h)
      Longitude: 0,           // 经度
      Latitude: 0,            // 纬度
      co2: 0,                 // 等效二氧化碳浓度(ppm)
      Tvoc: 0,                // 有机挥发物浓度(ppb)
      GasConcentration: 0,    // 气体浓度(%)
      Humidity: 0,            // 湿度(%RH)
      Temperature: 0          // 温度(℃)
    },
    warnings: {
      co2: false,             // CO2超阈值告警
      Tvoc: false,            // TVOC超阈值告警
      analogValue: false      // MQ-2超阈值告警
    },
    mqttConnected: false,
    hasWarnings: false,
    currentTime: '',
    showModal: false,
    currentSensor: '',
    currentValue: '',
    currentThreshold: '',
    newThreshold: '',
    // 报警弹窗控制
    alarmControl: {
      isShowingAlarm: false,  // 当前是否正在显示报警弹窗
      sensorAlarmCount: {     // 每个传感器的报警次数
        co2: 0,
        Tvoc: 0,
        analogValue: 0
      },
      maxAlarmCount: 1        // 每个传感器最大报警次数
    },
    sensorLabels: {
      CO2threshold: '二氧化碳阈值',
      Tvocthreshold: '有机挥发物阈值',
      MQthreshol: 'MQ-2阈值',
      Temperature: '环境温度',
      Humidity: '环境湿度',
      GasConcentration: '可燃气体浓度',
      Tvoc: '有机挥发物浓度',
      co2: '二氧化碳浓度',
      analogValue: 'MQ-2传感器原始值',
      Speed: 'GPS速度',
      Latitude: '纬度',
      Longitude: '经度',
      X: 'X轴加速度',
      Y: 'Y轴加速度',
      Z: 'Z轴加速度',
      boomswitch: '报警开关'
    },
    sensorUnits: {
      CO2threshold: '',
      Tvocthreshold: '',
      MQthreshol: '',
      Temperature: '℃',
      Humidity: '%RH',
      GasConcentration: '%',
      Tvoc: 'ppb',
      co2: 'ppm',
      analogValue: '',
      Speed: 'km/h',
      Latitude: '°',
      Longitude: '°',
      X: 'g',
      Y: 'g',
      Z: 'g',
      boomswitch: ''
    }
  },

  onLoad: function() {
    console.log('Dashboard页面加载');
    this.initMqtt();
    this.updateTime();
    this.startTimeTimer();
  },

  onShow: function() {
    console.log('Dashboard页面显示');
    this.startTimeTimer();
    
    // 使用全局的MQTT连接，不重复初始化
    const app = getApp();
    if (app.globalData.mqttClient) {
      this.setData({
        mqttConnected: app.globalData.mqttConnected
      });
      
      // 注册到App的数据分发系统
      app.registerPageDataCallback('dashboard', (data) => {
        console.log('Dashboard页面收到MQTT数据:', data);
        this.updateSensorData(data);
      });
      
      app.registerPageConnectionCallback('dashboard', (connected) => {
        console.log('Dashboard页面MQTT连接状态:', connected);
        this.setData({
          mqttConnected: connected
        });
        
        if (connected) {
          const attempts = app.globalData.mqttClient.getReconnectAttempts();
          if (attempts > 0) {
            wx.showToast({
              title: `重连成功(${attempts}次尝试)`,
              icon: 'success',
              duration: 2000
            });
            app.globalData.mqttClient.resetReconnectAttempts();
          }
        }
      });
    }
  },

  onHide: function() {
    console.log('Dashboard页面隐藏');
  },

  onUnload: function() {
    console.log('Dashboard页面卸载');
    this.cleanup();
    
    // 注销页面回调
    const app = getApp();
    app.unregisterPageCallbacks('dashboard');
  },

  initMqtt() {
    // 不再重复初始化MQTT，使用App全局的实例
    console.log('Dashboard使用App全局MQTT客户端');
  },

  updateSensorData(data) {
    if (!data || typeof data !== 'object') {
      console.warn('无效的传感器数据:', data);
      return;
    }

    const formattedData = {};
    Object.keys(this.data.sensorData).forEach(key => {
      if (data.hasOwnProperty(key)) {
        if (typeof data[key] === 'number') {
          formattedData[key] = Number(data[key].toFixed(1));
        } else {
          formattedData[key] = data[key];
        }
      }
    });

    this.setData({
      sensorData: { ...this.data.sensorData, ...formattedData }
    });

    this.checkWarnings();
  },

  checkWarnings() {
    const { sensorData, alarmControl } = this.data;
    const warnings = {};
    let hasWarnings = false;
    const newAlarms = []; // 存储新出现的报警

    // 检查CO2是否超过阈值
    const co2Exceeds = sensorData.co2 > sensorData.CO2threshold;
    warnings.co2 = co2Exceeds;
    if (co2Exceeds) {
      hasWarnings = true;
      // 如果是新的报警且未达到报警次数限制
      if (alarmControl.sensorAlarmCount.co2 < alarmControl.maxAlarmCount) {
        newAlarms.push('co2');
      }
    } else {
      // 传感器恢复正常时重置报警计数
      if (alarmControl.sensorAlarmCount.co2 > 0) {
        alarmControl.sensorAlarmCount.co2 = 0;
      }
    }

    // 检查TVOC是否超过阈值
    const tvocExceeds = sensorData.Tvoc > sensorData.Tvocthreshold;
    warnings.Tvoc = tvocExceeds;
    if (tvocExceeds) {
      hasWarnings = true;
      if (alarmControl.sensorAlarmCount.Tvoc < alarmControl.maxAlarmCount) {
        newAlarms.push('Tvoc');
      }
    } else {
      if (alarmControl.sensorAlarmCount.Tvoc > 0) {
        alarmControl.sensorAlarmCount.Tvoc = 0;
      }
    }

    // 检查MQ-2是否超过阈值
    const analogExceeds = sensorData.analogValue > sensorData.MQthreshol;
    warnings.analogValue = analogExceeds;
    if (analogExceeds) {
      hasWarnings = true;
      if (alarmControl.sensorAlarmCount.analogValue < alarmControl.maxAlarmCount) {
        newAlarms.push('analogValue');
      }
    } else {
      if (alarmControl.sensorAlarmCount.analogValue > 0) {
        alarmControl.sensorAlarmCount.analogValue = 0;
      }
    }

    this.setData({
      warnings,
      hasWarnings,
      alarmControl
    });

    // 只有在开启报警开关、有新的异常且当前没有显示报警弹窗时才触发报警
    if (sensorData.boomswitch && newAlarms.length > 0 && !alarmControl.isShowingAlarm) {
      this.triggerAlarmForSensors(newAlarms);
    }
  },

  triggerAlarmForSensors(sensors) {
    if (sensors.length === 0) return;
    
    const { sensorData, alarmControl } = this.data;
    
    // 设置正在显示报警状态
    alarmControl.isShowingAlarm = true;
    
    // 更新各传感器的报警计数
    sensors.forEach(sensor => {
      alarmControl.sensorAlarmCount[sensor]++;
    });
    
    this.setData({
      alarmControl
    });
    
    // 显示第一个传感器的报警
    this.showSensorAlarm(sensors[0], sensors.slice(1));
  },

  showSensorAlarm(currentSensor, remainingSensors) {
    const { sensorData } = this.data;
    let sensorName, currentValue, thresholdValue, unit;
    
    switch(currentSensor) {
      case 'co2':
        sensorName = 'CO₂浓度';
        currentValue = sensorData.co2;
        thresholdValue = sensorData.CO2threshold;
        unit = 'ppm';
        break;
      case 'Tvoc':
        sensorName = 'TVOC浓度';
        currentValue = sensorData.Tvoc;
        thresholdValue = sensorData.Tvocthreshold;
        unit = 'ppb';
        break;
      case 'analogValue':
        sensorName = 'MQ-2传感器';
        currentValue = sensorData.analogValue;
        thresholdValue = sensorData.MQthreshol;
        unit = '';
        break;
      default:
        return;
    }
    
    const message = `${sensorName}超标！\n当前值: ${currentValue}${unit}\n阈值: ${thresholdValue}${unit}\n请及时处理！`;
    
    wx.vibrateLong();
    wx.showModal({
      title: '传感器异常报警',
      content: message,
      showCancel: false,
      confirmText: '知道了',
      confirmColor: '#ff4d4f',
      complete: () => {
        // 当前弹窗关闭后，检查是否还有其他传感器需要报警
        if (remainingSensors.length > 0) {
          // 延迟500ms后显示下一个报警，避免弹窗重叠
          setTimeout(() => {
            this.showSensorAlarm(remainingSensors[0], remainingSensors.slice(1));
          }, 500);
        } else {
          // 所有报警都显示完毕，重置显示状态
          const { alarmControl } = this.data;
          alarmControl.isShowingAlarm = false;
          this.setData({
            alarmControl
          });
        }
      }
    });
  },

  showThresholdDialog(e) {
    const sensor = e.currentTarget.dataset.sensor;
    if (!sensor) return;

    const { sensorLabels, sensorUnits, sensorData } = this.data;
    
    // 判断是阈值变量还是数据变量，获取对应的阈值
    let thresholdKey, dataKey, currentValue, currentThreshold;
    
    if (sensor.endsWith('threshold')) {
      // 直接设置阈值变量
      thresholdKey = sensor;
      dataKey = sensor.replace('threshold', '').replace('MQthreshol', 'analogValue');
      if (sensor === 'CO2threshold') dataKey = 'co2';
      if (sensor === 'Tvocthreshold') dataKey = 'Tvoc';
    } else {
      // 从数据变量推导阈值变量
      if (sensor === 'co2') thresholdKey = 'CO2threshold';
      else if (sensor === 'Tvoc') thresholdKey = 'Tvocthreshold';  
      else if (sensor === 'analogValue') thresholdKey = 'MQthreshol';
      else return; // 不支持设置阈值的传感器
      
      dataKey = sensor;
    }

    currentValue = sensorData[dataKey];
    currentThreshold = sensorData[thresholdKey];
    const unit = sensorUnits[dataKey] || '';

    this.setData({
      showModal: true,
      currentSensor: sensorLabels[thresholdKey] || thresholdKey,
      currentValue: `${currentValue}${unit}`,
      currentThreshold: `${currentThreshold}${unit}`,
      newThreshold: currentThreshold.toString(),
      currentSensorKey: thresholdKey
    });
  },

  hideThresholdDialog() {
    this.setData({
      showModal: false,
      currentSensor: '',
      currentValue: '',
      currentThreshold: '',
      newThreshold: '',
      currentSensorKey: ''
    });
  },

  preventClose() {
    // 空函数，阻止事件冒泡
  },

  onThresholdInput(e) {
    this.setData({
      newThreshold: e.detail.value
    });
  },

  confirmThreshold() {
    const { newThreshold, currentSensorKey } = this.data;
    
    if (!newThreshold || !currentSensorKey) {
      wx.showToast({
        title: '请输入有效阈值',
        icon: 'none'
      });
      return;
    }

    const threshold = parseFloat(newThreshold);
    if (isNaN(threshold) || threshold <= 0) {
      wx.showToast({
        title: '请输入有效数值',
        icon: 'none'
      });
      return;
    }

    wx.showLoading({
      title: '设置中...'
    });

          const app = getApp();
      if (app.globalData.mqttClient && app.globalData.mqttConnected) {
        app.updateSensorData({
          [currentSensorKey]: threshold
        })
        .then(() => {
          const sensorData = { ...this.data.sensorData };
          sensorData[currentSensorKey] = threshold;
          
          this.setData({
            sensorData
          });

          wx.hideLoading();
          wx.showToast({
            title: '设置成功',
            icon: 'success'
          });

          this.hideThresholdDialog();
          
          this.checkWarnings();
        })
        .catch((error) => {
          console.error('阈值设置失败:', error);
          wx.hideLoading();
          wx.showToast({
            title: '设置失败，请重试',
            icon: 'none'
          });
        });
    } else {
      wx.hideLoading();
      wx.showToast({
        title: 'MQTT未连接，请检查网络',
        icon: 'none'
      });
    }
  },

  toggleAlarm(e) {
    const newState = e.detail.value ? 1 : 0;
    
    console.log('用户手动切换报警开关:', newState);
    
    // 更新页面状态
    this.setData({
      'sensorData.boomswitch': newState
    });

    const app = getApp();
    
    // 通过MQTT发送到云端并更新全局状态
    if (app.globalData.mqttClient && app.globalData.mqttConnected) {
      console.log('准备发送报警开关状态到MQTT:', { boomswitch: newState });
      
      app.updateSensorData({
        boomswitch: newState
      }).then(() => {
        console.log('报警开关状态发送成功');
        wx.showToast({
          title: newState ? '报警已开启并同步' : '报警已关闭并同步',
          icon: 'success',
          duration: 2000
        });
      }).catch(error => {
        console.error('报警开关同步失败:', error);
        wx.showToast({
          title: '同步失败，请检查网络',
          icon: 'none',
          duration: 2000
        });
        
        // 发送失败时恢复原状态
        const originalState = newState === 1 ? 0 : 1;
        this.setData({
          'sensorData.boomswitch': originalState
        });
      });
    } else {
      console.warn('MQTT未连接，无法同步报警开关状态');
      wx.showToast({
        title: 'MQTT未连接，仅本地生效',
        icon: 'none',
        duration: 2000
      });
    }
  },

  updateTime() {
    const now = new Date();
    const timeString = now.toLocaleTimeString('zh-CN', {
      hour12: false,
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });
    
    this.setData({
      currentTime: timeString
    });
  },

  startTimeTimer() {
    this.timeTimer = setInterval(() => {
      this.updateTime();
    }, 1000);
  },

  cleanup() {
    if (this.timeTimer) {
      clearInterval(this.timeTimer);
      this.timeTimer = null;
    }
    
    // 不再断开全局MQTT连接，让App管理
  }
}) 